package com.module.reading;

import com.module.common.utils.RedisUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

@Slf4j
@Component
public class NettyServer implements CommandLineRunner {

    //boss事件轮询线程组
    //处理Accept连接事件的线程，这里线程数设置为1即可，netty处理链接事件默认为单线程，过度设置反而浪费cpu资源
    private EventLoopGroup boss = new NioEventLoopGroup(1);
    //worker事件轮询线程组
    //处理hadnler的工作线程，其实也就是处理IO读写 。线程数据默认为 CPU 核心数乘以2
    private EventLoopGroup worker = new NioEventLoopGroup(20);

    @Autowired
    private NettyInitializer nettyInitializer;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    @Async
    public void run(String... args) throws Exception {
        //启动类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            //组配置，初始化ServerBootstrap的线程组
            serverBootstrap.group(boss, worker)
                    ///构造channel通道工厂//bossGroup的通道，只是负责连接
                    .channel(NioServerSocketChannel.class)
                    //设置通道处理者ChannelHandler////workerGroup的处理器
                    .childHandler(nettyInitializer)
                    //保持连接数
                    .option(ChannelOption.SO_BACKLOG, 65535)
                    //数据长度
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024 * 1024))
                    //启用心跳保活机制，tcp，默认2小时发一次心跳
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            //Future：异步任务的生命周期，可用来获取任务结果
            //绑定端口，开启监听，同步等待
            ChannelFuture channelFuture = serverBootstrap.bind(3322).sync();
            if (channelFuture != null && channelFuture.isSuccess()) {
                log.info("电表TCP服务器启动成功");
                channelFuture.channel().closeFuture().sync();
            } else {
                log.error("电表TCP服务器启动失败");
            }
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    /**
     * 停止Netty tcp server服务
     */
    @PreDestroy
    public void destroy() {
        try {
            Future<?> future = worker.shutdownGracefully().await();
            if (!future.isSuccess()) {
                log.error("netty tcp workerGroup shutdown fail, {}", future.cause());
            }
            Future<?> future1 = boss.shutdownGracefully().await();
            if (!future1.isSuccess()) {
                log.error("netty tcp bossGroup shutdown fail, {}", future1.cause());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        redisUtils.hdelAll("device_online");
        log.info("TCP服务器关闭");
    }
}
